//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  ActivitiesBoard.m
//  iHeima
//
//  Created by he chao on 5/27/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "ActivitiesBoard.h"
#import "PostActivityBoard.h"
#import "ActivityDetailBoard.h"
#import "CityBoard.h"
#import "CategoryBoard.h"
#import "SearchActivityBoard.h"
#import "ActivityCell.h"

#pragma mark -

@interface ActivitiesBoard()
{
	//<#@private var#>
    NSMutableArray* _images;
    
    NSMutableArray* _activityTimeLines;
    
}
@end

@implementation ActivitiesBoard
DEF_SIGNAL(CATEGORY)
DEF_SIGNAL(CITY)

- (void)load
{
    self.strCategory = @"全部行业";
    self.strCity = @"北京";
    selCategory = 0;
    selProvince = 0;
    selCity = 0;
   
}

- (void)unload
{
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    //self.title = @"活动";
    
  
    
    [self showNaviBar];
    self.navigationController.navigationBarHidden = NO;
    [self showBarButton:BeeUINavigationBar.LEFT image:IMAGESTRING(@"navi_search")];
    [self showBarButton:BeeUINavigationBar.RIGHT image:IMAGESTRING(@"navi_write")];
    
    BeeUIButton *btn = [BeeUIButton spawn];
    btn.frame = CGRectMake(100, 100, 100, 100);
    btn.backgroundColor = [UIColor yellowColor];
    [btn addTarget:self action:@selector(detail) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    //NSLog(@"%@",[BeeSystemInfo appVersion]);

    
    [self getCategory];
    [self getCityList];
    [self getActivityList];
    [self getAdsList];
    
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.viewWidth, self.viewHeight-50-(IOS7_OR_LATER?64:44))];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
    
    //[self loadBannerView];
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if (!labelCategory) {
        labelCategory = [BeeUILabel spawn];
        labelCategory.textColor = kNormalColor;
        labelCategory.font = FONT(15);
        [labelCategory makeTappable:ActivitiesBoard.CATEGORY];
    }
    [self.navigationController.navigationBar addSubview:labelCategory];
    if (!labelCity) {
        labelCity = [BeeUILabel spawn];
        labelCity.textColor = kNormalColor;
        labelCity.font = FONT(12);
        [labelCity makeTappable:ActivitiesBoard.CITY];
    }
    [self.navigationController.navigationBar addSubview:labelCity];
    if (!arrow1) {
        arrow1 = [BeeUIImageView spawn];
        [arrow1 makeTappable:ActivitiesBoard.CATEGORY];
        arrow1.image = IMAGESTRING(@"navi_arrow");
    }
    [self.navigationController.navigationBar addSubview:arrow1];
    if (!arrow2) {
        arrow2 = [BeeUIImageView spawn];
        [arrow2 makeTappable:ActivitiesBoard.CITY];
        arrow2.image = IMAGESTRING(@"navi_arrow");
    }
    [self.navigationController.navigationBar addSubview:arrow2];
    
    labelCategory.text = self.strCategory;
    CGSize sz1 = [labelCategory.text sizeWithFont:labelCategory.font byWidth:200];
    labelCategory.frame = CGRectMake((self.viewWidth-sz1.width)/2.0, 0, sz1.width, 44);
    
    arrow1.frame = CGRectMake(labelCategory.right, 0, 15, 44);
    
    arrow2.frame = CGRectMake(self.viewWidth-15-50, 0, 15, 44);
    
    
    labelCity.text = self.strCity;
    CGSize sz2 = [labelCity.text sizeWithFont:labelCity.font byWidth:200];
    labelCity.frame = CGRectMake(arrow2.left-sz2.width, 0, sz2.width, 44);
    
    labelCity.hidden = YES;
    arrow2.hidden = YES;
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
    [labelCategory removeFromSuperview];
    [labelCity removeFromSuperview];
    [arrow1 removeFromSuperview];
    [arrow2 removeFromSuperview];
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    [[MainBoard sharedInstance].stack presentViewController:[BeeUIStack stack:nil firstBoard:[[SearchActivityBoard alloc] init]] animated:YES completion:nil];
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
    [[MainBoard sharedInstance].stack pushBoard:[[PostActivityBoard alloc] init] animated:YES];
}

ON_SIGNAL2(ActivitiesBoard, signal) {
    if ([signal is:ActivitiesBoard.CATEGORY]) {
//        CategoryBoard *board = [[CategoryBoard alloc] init];
//        [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
//        
        BeeUIPickerView *myPickerView = [BeeUIPickerView spawn];
        for (int i = 0; i < arrayCategory.count; i++) {
            [myPickerView addTitle:arrayCategory[i][@"name"]];
        }
        myPickerView.tag = 9527;
        [myPickerView selectRow:selCategory inComponent:0 animated:YES];
        [myPickerView showInViewController:self];
    }
    else if ([signal is:ActivitiesBoard.CITY]) {
        BeeUIPickerView *myPickerView = [BeeUIPickerView spawn];
        [myPickerView setColumns:2];
        myPickerView.tag = 9528;
        for (int i = 0; i < arrayCity.count; i++) {
            [myPickerView addTitle:arrayCity[i][@"name"] forColumn:0];
        }
        //
        
        NSArray *arrayChild = arrayCity[selProvince][@"child"];
        for (int i = 0; i < arrayChild.count; i++) {
            [myPickerView addTitle:arrayChild[i][@"name"] forColumn:1];
        }
        
        //
        
        [myPickerView showInViewController:self];
        
//        [myPickerView pickerView:myPickerView didSelectRow:selProvince inComponent:0];
//        [myPickerView pickerView:myPickerView didSelectRow:selCity inComponent:1];
        [myPickerView selectRow:selProvince inComponent:0 animated:YES];
        [myPickerView selectRow:selCity inComponent:1 animated:YES];
        
        [myPickerView setSelRowIndex:selProvince inComponent:0];
        [myPickerView setSelRowIndex:selCity inComponent:1];
        
//        CityBoard *board = [[CityBoard alloc] init];
//        [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
    }
}

ON_SIGNAL2(BeeUIPickerView, signal) {
    BeeUIPickerView *picker = (BeeUIPickerView *)signal.source;
    if ([signal is:BeeUIPickerView.CONFIRMED]) {
        switch (picker.tag) {
            case 9527:
            {
                selCategory = [picker selectedRowInComponent:0];
                dictCategory = arrayCategory[selCategory];
                self.strCategory = dictCategory[@"name"];
                strCategoryId = dictCategory[@"id"];
                [self getActivityList];
                
                [self sendUISignal:BeeUIBoard.WILL_APPEAR];
            }
                break;
            case 9528:
            {
                selProvince = [picker selectedRowInColumn:0];
                selCity = [picker selectedRowInColumn:1];
                self.strCity = [picker selectedTitleInColumn:1];
                
                [self sendUISignal:BeeUIBoard.WILL_APPEAR];
            }
                break;
                
            default:
                break;
        }
    }
    else if ([signal is:BeeUIPickerView.CHANGED]) {
        if (picker.tag == 9528) {
            int index = [picker selectedRowInComponent:0];
            if (index != selProvince) {
                [picker removeTitlesForColumn:1];
                NSArray *arrayCity1 = arrayCity[index][@"child"];
                for (int i = 0; i < [arrayCity1 count]; i++) {
                    [picker addTitle:arrayCity1[i][@"name"] forColumn:1];
                }
                [picker reloadAllComponents];
                
                selProvince = index;
                selCity = 0;
                [picker selectRow:selCity inComponent:1 animated:YES];
            }
            
        }
    }
    
}



- (void)loadBannerView{
    
    _images = [NSMutableArray array];
    [bannerView removeFromSuperview];
    bannerView = nil;
    NSInteger length = [arrayAds count];
    
    NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:6];
    for (int i = 0; i < length+2; i++) {
        //UIView *vi = [[UIView alloc] init];
        BeeUIImageView *vi = [BeeUIImageView spawn];
        vi.frame = CGRectMake(0, 0, 320, 126);
        vi.contentMode = UIViewContentModeScaleToFill;
        vi.image = IMAGESTRING(@"demo@2x.png");
        
        if (i == 0) {
            vi.tag = -1;
            vi.url = [NSString stringWithFormat:@"%@/%@",kBaseUrl,arrayAds[length-1][@"path"]];//[arrayAds objectAtIndex:length-1];
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toDetail:)];
            [vi addGestureRecognizer:tap];
            vi.userInteractionEnabled = YES;
            [_images addObject:vi];
        }
        else if (i == length+1){
            vi.tag = length;
            vi.url = [NSString stringWithFormat:@"%@/%@",kBaseUrl,arrayAds[0][@"path"]];
            //vi.url = [arrayAds objectAtIndex:0];
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toDetail:)];
            [vi addGestureRecognizer:tap];
            vi.userInteractionEnabled = YES;
            [_images addObject:vi];
        }
        else {
            vi.tag = i-1;
            vi.url = [NSString stringWithFormat:@"%@/%@",kBaseUrl,arrayAds[i-1][@"path"]];
            //vi.url = [arrayAds objectAtIndex:i-1];
            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toDetail:)];
            [vi addGestureRecognizer:tap];
            vi.userInteractionEnabled = YES;
            [_images addObject:vi];
        }
        
        [itemArray addObject:vi];
    }
    
    bannerView = [[ScrollLoopView alloc] initWithFrame:CGRectMake(0, 60+10, 320, 126) delegate:self views:itemArray isAuto:YES];
    [bannerView scrollToIndex:0];
    myTableView.tableHeaderView = bannerView;
    //[myScrollView addSubview:bannerView];
}

- (void)getCityList{
    id value = [[BeeFileCache sharedInstance] objectForKey:@"city"];
    if (value) {
        arrayCity = [(NSData *)value objectFromJSONData];
       // NSLog(@"%@",arrayCity);
    }
    else {
        BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apidistrict/getdistrict/",kBaseUrl]];
        request.tag = 9527;
    }
}

- (void)getCategory{
    id value = [[BeeFileCache sharedInstance] objectForKey:@"category"];
    if (value) {
        arrayCategory = [(NSData *)value objectFromJSONData];
        //NSLog(@"%@",arrayCategory);
    }
    else {
        BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apitrade/gettrade/",kBaseUrl]];
        request.tag = 9528;
    }
}

- (void)getActivityList{
    BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apiactivity/lists/",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]);
    if (strCategoryId) {
        request.PARAM(@"trade_id",strCategoryId);
    }
    request.tag = 9529;
}

- (void)getAdsList{
    BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apiapp/adslist/",kBaseUrl]];

    request.tag = 9530;
}

- (void)detail{
    ActivityDetailBoard *board = [[ActivityDetailBoard alloc] init];
    [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
}

- (void)handleRequest:(BeeRequest *)request
{
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        id json = [request.responseString mutableObjectFromJSONString];
        
        switch ([json[@"status"] intValue]) {
            case 1:
            {
                switch (request.tag) {
                    case 9527:
                    {
                        [[BeeFileCache sharedInstance] setObject:[json[@"res"] JSONData] forKey:@"city"];
                        
                        NSLog(@"城市信息:%@",json[@"res"]);
                        
                        
                    }
                        break;
                    case 9528:
                    {
                        [[BeeFileCache sharedInstance] setObject:[json[@"res"] JSONData] forKey:@"category"];
                        
                       // NSDictionary* dic =  (NSDictionary*)json;
                        //printf("-------%s",dic);
                        
                        NSLog(@"分类信息:%@",json[@"res"]);
                        
                        
                    }
                        break;
                    case 9529:
                    {
                        arrayActivities = json[@"res"];
                        NSLog(@"活动信息:%@",json[@"res"]);
                        
                        
                        
                        
                        [myTableView reloadData];
                      
                    }
                        break;
                    case 9530:
                    {
                        arrayAds = json[@"res"];
                        [self loadBannerView];
                        
                        NSLog(@"滚动广告信息:%@",json[@"res"]);
                        
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
        }
    }
}




- (void)toDetail:(UITapGestureRecognizer*)sender{
    
    ActivityDetailBoard *board = [[ActivityDetailBoard alloc] init];
    board.isFromScroll = YES;
    
    for (BeeUIImageView* iv in _images) {
        if (iv.tag == -10) {
            
            NSDictionary* dic = arrayAds[0];
            board.webUrl = [dic objectForKey:@"url"];
            
            
        }else if (iv.tag == 34)
        {
            NSDictionary* dic = arrayAds[1];
            board.webUrl = [dic objectForKey:@"url"];
        }else{
            NSDictionary* dic = arrayAds[2];
            board.webUrl = [dic objectForKey:@"url"];
        }
    }
    [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [arrayActivities count];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (nil == cell) {
        cell = [[ActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        [cell initSelf];
    }
    cell.backgroundColor = [UIColor clearColor];
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dictActivity = arrayActivities[indexPath.row];
    [cell load];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ActivityDetailBoard *board = [[ActivityDetailBoard alloc] init];
    board.dictActivity = arrayActivities[indexPath.row];
    [[MainBoard sharedInstance].stack pushBoard:board animated:YES];
}

@end
